package com.yuanmei.views;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.yuanmei.charts.BottomMarkerView;
import com.yuanmei.charts.CoupleValueSelectedListener;
import com.yuanmei.charts.GroupGestureListener;
import com.yuanmei.charts.HorizontalMarkerView;
import com.yuanmei.charts.LeftMarkerView;
import com.yuanmei.charts.TaCombinedChart;
import com.yuanmei.charts.TickQuoteDataSet;
import com.yuanmei.datas.DBUtils;
//import com.yuanmei.model.TdxStockInfo;
import com.yuanmei.model.TickQuote;
import com.yuanmei.model.TodayQuote;
import com.yuanmei.common.Utils;
import com.yuanmei.datas.FetchTickDaemon;
import com.yuanmei.datas.FetchTickDaemon.EmTickType;

//import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
//import java.util.Timer;
//import java.util.TimerTask;

public class TickQuoteChartActivity extends Activity
        implements CoupleValueSelectedListener.OnDataIndexChangedListener,
        TickQuoteListAdapter.ItemClickListener, FetchTickDaemon.FetchRealTimeTickListener,
        QuickStockApplication.NotifyMessageCallback {
    private final static String TAG = TickQuoteChartActivity.class.getSimpleName();
    protected static final int MSG_UPDATE_CHARTS = 1;
    protected static final int MSG_SHOW_TOAST = 2;
    protected static final int MSG_UPDATE_PROGRESS = 3;
    protected static final int MSG_SHOW_PROGRESS_BAR = 4;
    protected static final int MSG_HIDE_PROGRESS_BAR = 5;

    private TextView mTvName, mTvCode, mTvDate;
    private TextView mTvTime, mTvVolume, mTvPrice, mTvAmount, mTvType;

    private TaCombinedChart mPriceChart;
    private TaCombinedChart mAmountChart;
    TextView mStartStatTickQuoteButton;
    //    private TdxStockInfo mStockBasicInfo;
    private TickQuoteDataSet mTimeShareData;
    private TodayQuote mFlushTodayQuote = null;

    private void startStatTickQuotesActivity() {
        if (mTimeShareData == null) {
            Toast.makeText(this,
                    "分时数据为空，不能启动统计分析", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(TickQuoteChartActivity.this,
                TickQuoteStatActivity.class);
        intent.putExtra("Name", mName);
        intent.putExtra("NetEaseCode", mNetEaseCode);
        intent.putExtra("IsMarketIndex", mIsMarketIndex);
        intent.putExtra("XDate", mTickIDate);
        startActivity(intent);
    }

//    private void startQiMenStudyApp() {
//        //启动 奇门学习 应用
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addCategory(Intent.CATEGORY_LAUNCHER);
//        ComponentName cn = new ComponentName("com.yuanmei.qmstudy",
//                "com.yuanmei.qmstudy.QiMenMainActivity");
//        intent.setComponent(cn);
//        int timeToMarket = 19700101;
//        if (mFinanceBasics != null) {
//            timeToMarket = mFinanceBasics.getTimeToMarket();
//        }
//
//        intent.putExtra("StockName", mName);
//        intent.putExtra("StockCode", mNetEaseCode.substring(1));
//        intent.putExtra("StockTimeToMarket", timeToMarket);
//        intent.putExtra("StockDate", mTickIDate);
//        String tick = mTimeShareData.getXAxisLabel(mSelectedDataIndex);
//        intent.putExtra("StockTick", tick);
//        startActivity(intent);
//
//        Toast.makeText(this,
//                "奇门功能已关闭",
//                Toast.LENGTH_SHORT).show();
//    }

    private void refreshTickData() {
        EmTickType type = EmTickType.STOCK_HISTORY;
        if (isTodayTick()) {
            if (mIsMarketIndex) {
                type = EmTickType.INDEX_REAL_TIME;
            } else {
                type = EmTickType.STOCK_REAL_TIME;
            }
        }
        FetchTickDaemon.getInstance().startPriorFetch(mNetEaseCode, type, mTickDate);
        Toast.makeText(this,
                "已启动Tick数据刷新", Toast.LENGTH_SHORT).show();
    }

    private void clearAndDownloadTickData() {
        Utils.clearTickQuotesOfRealm(mNetEaseCode, mTickDate);

        EmTickType type = EmTickType.STOCK_HISTORY;
        if (isTodayTick()) {
            if (mIsMarketIndex) {
                type = EmTickType.INDEX_REAL_TIME;
            } else {
                type = EmTickType.STOCK_REAL_TIME;
            }
        }
        FetchTickDaemon.getInstance().startPriorFetch(mNetEaseCode, type, mTickDate);
        Toast.makeText(this,
                "已启动重新下载数据", Toast.LENGTH_SHORT).show();
    }

    private void initTextViews() {
        mTvName = findViewById(R.id.ts_name);
        mTvCode = findViewById(R.id.ts_code);
        mTvDate = findViewById(R.id.ts_date);
        mTvTime = findViewById(R.id.ts_time);
        mTvPrice = findViewById(R.id.ts_price);
        mTvVolume = findViewById(R.id.ts_volume);
        mTvAmount = findViewById(R.id.ts_amount);
        mTvType = findViewById(R.id.ts_type);

        mTvBuyDetails = findViewById(R.id.buy_details);
        mTvSellDetails = findViewById(R.id.sell_details);

        mPriceChart = findViewById(R.id.ts_price_chart);
        mAmountChart = findViewById(R.id.ts_amount_chart);

        TextView startEastMoneyBt = findViewById(R.id.start_east_money_bt);
        startEastMoneyBt.setOnClickListener(view -> {
            Intent intent =
                    new Intent(TickQuoteChartActivity.this,
                            EastMoneyViewActivity.class);
            intent.putExtra("Name", mName)
                    .putExtra("NetEaseCode", mNetEaseCode)
                    .putExtra("IsMarketIndex", mIsMarketIndex);
            startActivity(intent);
        });

//        TextView startQiMenBt = findViewById(R.id.start_qimen_bt);
//        startQiMenBt.setOnClickListener(view -> startQiMenStudyApp());

        TextView refreshTickBt = findViewById(R.id.refresh_tick_bt);
        refreshTickBt.setOnClickListener(view -> refreshTickData());

        TextView reloadTickBt = findViewById(R.id.reload_tick_bt);
        reloadTickBt.setOnClickListener(view -> clearAndDownloadTickData());

        mStartStatTickQuoteButton = findViewById(R.id.start_stat_tick_quote_bt);
        mStartStatTickQuoteButton.setOnClickListener(view -> startStatTickQuotesActivity());
        mStartStatTickQuoteButton.setEnabled(false);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    private void initCommonTaChartStyle(TaCombinedChart taChart) {
        taChart.setDrawBorders(true);
        taChart.setBorderWidth(1);

        taChart.setTouchEnabled(true);
        taChart.setDragEnabled(true);
        taChart.setScaleEnabled(true);
        taChart.setPinchZoom(true);
        taChart.setDoubleTapToZoomEnabled(false);

        taChart.setBorderColor(getResources().getColor(R.color.border_color));
        taChart.setDescription(new Description());
        taChart.setMinOffset(0f);
        taChart.setExtraOffsets(0f, 0f, 0f, 3f);
        taChart.getLegend().setEnabled(false);

        taChart.setDragDecelerationEnabled(true);
        taChart.setDragDecelerationFrictionCoef(0.2f);

        taChart.animateXY(1000, 1000);

        taChart.getAxisRight().setEnabled(false);

        XAxis xAxis = taChart.getXAxis();
        xAxis.setAxisMinimum(-1f);

        YAxis leftYAxis = taChart.getAxisLeft();
        leftYAxis.setDrawGridLines(true);
        leftYAxis.setDrawAxisLine(false);
        leftYAxis.setDrawLabels(true);
        leftYAxis.enableGridDashedLine(10f, 10f, 0f);
        leftYAxis.setTextColor(getResources().getColor(R.color.text_color_common));
        leftYAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        leftYAxis.setLabelCount(4, false);
        leftYAxis.setSpaceTop(4);//距离顶部留白

        LeftMarkerView leftMarkerView = new LeftMarkerView(this, R.layout.marker_text_view);
        BottomMarkerView bottomMarkerView = new BottomMarkerView(this, R.layout.marker_text_view);
        taChart.setLeftMarkerView(leftMarkerView);
        taChart.setBottomMarkerView(bottomMarkerView);
    }

    private void initPriceChart() {
        initCommonTaChartStyle(mPriceChart);
        mPriceChart.getDescription().setEnabled(false);
        //bar x y轴
        XAxis xAxis = mPriceChart.getXAxis();
        xAxis.setDrawLabels(true);
        xAxis.setDrawGridLines(false);//是否显示X坐标轴上的刻度竖线，默认是true
        xAxis.setDrawAxisLine(false); //是否绘制坐标轴的线，即含有坐标的那条线，默认是true
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setTextColor(getResources().getColor(R.color.text_color_common));//设置字的颜色
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置值显示在什么位置
        xAxis.setAvoidFirstLastClipping(true);//设置首尾的值是否自动调整，避免被遮挡

        HorizontalMarkerView hMarkerView = new HorizontalMarkerView(this, R.layout.marker_line_view);
        mPriceChart.setHorizontalMarkerView(hMarkerView);
    }

    private void initAmountCharts() {
        initCommonTaChartStyle(mAmountChart);
        mAmountChart.getDescription().setEnabled(false);
        mAmountChart.getXAxis().setEnabled(false);

        YAxis leftYAxis = mAmountChart.getAxisLeft();
        leftYAxis.setLabelCount(1, true);
        leftYAxis.setDrawZeroLine(true); // draw a zero line
        leftYAxis.setZeroLineColor(Color.GRAY);
        leftYAxis.setZeroLineWidth(0.7f);
    }

    private void updateTextViewToXIndex(int index) {
        mTvName.setText(mName);
        mTvCode.setText(mNetEaseCode.substring(1));
        mTvDate.setText(sDateFormat.format(mTickDate));
        if (mFlushTodayQuote == null) {
            mTvBuyDetails.setText(mTodayBuys);
            mTvSellDetails.setText(mTodaySells);
        } else {
            mTvBuyDetails.setText(mFlushTodayQuote.getBuys());
            mTvSellDetails.setText(mFlushTodayQuote.getSells());
        }
        if (index >= 0 && index < mTimeShareData.getXAxisSize()) {
            float price = mTimeShareData.getPrice(index);
            mTvTime.setText(mTimeShareData.getXAxisLabel(index));
            mTvPrice.setText(Utils.priceToDecimalString(price));
            mTvVolume.setText(Utils.volumeToShortUnit(mTimeShareData.getVolume(index)));
            mTvAmount.setText(Utils.amountToShortUnit(mTimeShareData.getAmount(index)));
            mTvType.setText(mTimeShareData.getType(index));
        }
    }

    private int mSelectedDataIndex = -1;

    public void onSelectedDataIndexChanged(int index) {
        mSelectedDataIndex = index;
        updateTextViewToXIndex(index);

        // 分时明细窗口
        int listIdx = mLeftLayoutManager.getItemCount() - 1 - index;
        mLeftLayoutManager.scrollToPositionWithOffset(listIdx, 0);
        mLeftTickListAdapter.setCurrentClickPosition(listIdx);
        int last = mLeftLayoutManager.findLastCompletelyVisibleItemPosition();
        int first = mLeftLayoutManager.findFirstCompletelyVisibleItemPosition();
        if (last > first) {
            int range = (last - first) + 1;
            mRightLayoutManager.scrollToPositionWithOffset(
                    Math.min(listIdx + range - 1, mTimeShareData.getXAxisSize()), 0);
        }
        mLeftTickListAdapter.notifyDataSetChanged();
        mRightTickListAdapter.notifyDataSetChanged();
    }

    private void resetSyncListener() {
        // Gesture 同步
        mPriceChart.setOnChartGestureListener(
                new GroupGestureListener(mPriceChart,
                        new TaCombinedChart[]{mAmountChart},
                        null));
        mAmountChart.setOnChartGestureListener(
                new GroupGestureListener(mAmountChart,
                        new TaCombinedChart[]{mPriceChart},
                        null));

        // 高亮选择同步
        mPriceChart.setOnChartValueSelectedListener(
                new CoupleValueSelectedListener(mPriceChart, mAmountChart, this));
        mAmountChart.setOnChartValueSelectedListener(
                new CoupleValueSelectedListener(mAmountChart, mPriceChart, this));
    }

    private class TickAxisFormatter implements IAxisValueFormatter {
        List<String> mTickLabels;

        TickAxisFormatter(List<String> iTicks) {
            this.mTickLabels = iTicks;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            int i = (int) value % mTickLabels.size();
            return mTickLabels.get(i);
//            return Utils.formatStringFromTick(tick);
        }
    }

    private String mName;
    private String mNetEaseCode;
    private Boolean mIsMarketIndex;
    private Date mTickDate;
    private int mTickIDate;
//    private FetchDataService.FetchDataBinder mFetchBinder;

    private void updateTimeShareChartData(TickQuoteDataSet tsData, int viewX) {
        mPriceChart.setData(tsData.getTaChartData());
//        mPriceChart.setVisibleXRangeMaximum(1000);
        mPriceChart.moveViewToX(viewX);
        mPriceChart.setAutoScaleMinMaxEnabled(true);
        mPriceChart.setTaChartData(tsData);
//        float xAxisMax = mPriceChart.getCombinedData().getXMax() + 1f;
        float xAxisMax = tsData.getXAxisSize() + 1f;
        mPriceChart.getXAxis().setAxisMaximum(xAxisMax);
        mPriceChart.getXAxis().setValueFormatter(new TickAxisFormatter(tsData.getXAxisLabelList()));

        mAmountChart.setData(tsData.getAmountChartData());
        mAmountChart.moveViewToX(viewX);
        mAmountChart.setAutoScaleMinMaxEnabled(true);
        mAmountChart.setTaChartData(tsData);
        mAmountChart.getXAxis().setAxisMaximum(xAxisMax);
        mAmountChart.getXAxis().setValueFormatter(new TickAxisFormatter(tsData.getXAxisLabelList()));
    }

    private void refreshTickDetailPanel() {
        // 左边
        mLeftTickListAdapter = new TickQuoteListAdapter(mTimeShareData.getDescendTickQuotes());
        mLeftTickList.setAdapter(mLeftTickListAdapter);
        mLeftTickListAdapter.setClickListener(this);
        mLeftLayoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        mLeftTickList.setLayoutManager(mLeftLayoutManager);
        mLeftTickList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int last = mLeftLayoutManager.findLastCompletelyVisibleItemPosition();
                int first = mLeftLayoutManager.findFirstCompletelyVisibleItemPosition();
                if (last > first) {
                    int range = last - first + 1;
                    mRightLayoutManager.scrollToPositionWithOffset(
                            Math.min(last + range - 1, mTimeShareData.getXAxisSize()), 0);
                }
            }
        });
        mLeftTickListAdapter.setCurrentClickPosition(0);

        // 右边
        mRightTickListAdapter = new TickQuoteListAdapter(mTimeShareData.getDescendTickQuotes());
        mRightTickList.setAdapter(mRightTickListAdapter);
        mRightTickListAdapter.setClickListener(this);
        mRightLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRightTickList.setLayoutManager(mRightLayoutManager);
        mRightTickList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                int first = mRightLayoutManager.findFirstCompletelyVisibleItemPosition();
                mLeftLayoutManager.scrollToPositionWithOffset(Math.max(first, 0), 0);
            }
        });
        mRightLayoutManager.scrollToPositionWithOffset(8, 0);
        mRightTickListAdapter.setCurrentClickPosition(-1);
    }

    private void updateDownloadProgress(int progressPercent) {
        if (mDownloadProgressBar.getVisibility() == View.VISIBLE) {
            mDownloadProgressBar.setProgress(progressPercent);
        }
    }

    private void showDownloadProgressBar() {
        mDownloadProgressBar.setVisibility(View.VISIBLE);
    }

    private void hideDownloadProgressBar() {
        mDownloadProgressBar.setVisibility(View.INVISIBLE);
    }

    private void refreshCharts() {
        mSelectedDataIndex = mTimeShareData.getRealTickQuoteSize() - 1;
        updateTimeShareChartData(mTimeShareData, mSelectedDataIndex);
        Log.d(TAG, "JKP refresh Charts index=" + mSelectedDataIndex);
        updateTextViewToXIndex(mSelectedDataIndex);
        resetSyncListener();

        mTvBigSeek.setText(String.format(Locale.CHINA,
                "大单比例:%.2f%% 分界单笔:%.2f万 %d手",
                mBigQuoteScale * 100, mTimeShareData.getDivideAmount() / 10000,
                (int) mTimeShareData.getDivideVolume() / 100
        ));

        // 分时列表
        if (mDetailsPanel.getVisibility() == View.VISIBLE) {
            refreshTickDetailPanel();
        }
        mStartStatTickQuoteButton.setEnabled(true);
    }

    private static class ActivityMessageHandler extends Handler {
        private final WeakReference<TickQuoteChartActivity> mWeakActivity;

        private ActivityMessageHandler(TickQuoteChartActivity tsActivity) {
            mWeakActivity = new WeakReference<>(tsActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            TickQuoteChartActivity tsActivity = mWeakActivity.get();
            if (tsActivity == null)
                return;

            switch (msg.what) {
                case MSG_UPDATE_CHARTS:
                    tsActivity.refreshCharts();
                    break;
                case MSG_SHOW_TOAST:
                    Toast.makeText(tsActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    break;
                case MSG_UPDATE_PROGRESS:
                    tsActivity.updateDownloadProgress((int) msg.obj);
                    break;
                case MSG_SHOW_PROGRESS_BAR:
                    tsActivity.showDownloadProgressBar();
                    break;
                case MSG_HIDE_PROGRESS_BAR:
                    tsActivity.hideDownloadProgressBar();
                    break;
                default:
                    break;
            }
        }
    }

    private Handler mHandler;
    private final static SimpleDateFormat sDateFormat
            = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    private RecyclerView mLeftTickList;
    private LinearLayoutManager mLeftLayoutManager;
    private TickQuoteListAdapter mLeftTickListAdapter;
    private RecyclerView mRightTickList;
    private LinearLayoutManager mRightLayoutManager;
    private TickQuoteListAdapter mRightTickListAdapter;
    private LinearLayout mDetailsPanel;
    private ProgressBar mDownloadProgressBar;

    @Override
    public void onRecycleListItemClick(RecyclerView.Adapter adapter, View view, int position) {
        if (adapter == mLeftTickListAdapter) {
            mLeftTickListAdapter.setCurrentClickPosition(position);
            mRightTickListAdapter.setCurrentClickPosition(-1);
        } else {
            mLeftTickListAdapter.setCurrentClickPosition(-1);
            mRightTickListAdapter.setCurrentClickPosition(position);
        }
        mLeftTickListAdapter.notifyDataSetChanged();
        mRightTickListAdapter.notifyDataSetChanged();

        int x = mTimeShareData.mapDescendIndexToAscendIndex(position);
        if (x >= 0) {
            Highlight hiLight = new Highlight(x, mTimeShareData.getPrice(x), 0);
            hiLight.setDataIndex(0);
            mPriceChart.highlightValues(new Highlight[]{hiLight});
            hiLight = new Highlight(x, mTimeShareData.getAmount(x), 0);
            hiLight.setDataIndex(0);
            mAmountChart.highlightValues(new Highlight[]{hiLight});
            updateTextViewToXIndex(x);
        }
    }

    private TextView mTvBigSeek;
    private TextView mTvBuyDetails, mTvSellDetails;
    private float mBigQuoteScale = 0.2f;
    private String mTodayBuys, mTodaySells;
    private float mYesTodayClose;

    @Override
    public void onPause() {
        super.onPause();
        FetchTickDaemon.getInstance().unregisterListener(this);
        QuickStockApplication.unregisterNotifyCallback(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        FetchTickDaemon.getInstance().registerListener(this);
        QuickStockApplication.registerNotifyCallback(this);
        refreshTickData();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mName = getIntent().getStringExtra("Name");
        mNetEaseCode = getIntent().getStringExtra("NetEaseCode");
        mIsMarketIndex = getIntent().getBooleanExtra("IsMarketIndex", false);
        mTodayBuys = getIntent().getStringExtra("TodayBuys");
        mTodaySells = getIntent().getStringExtra("TodaySells");
        mYesTodayClose = getIntent().getFloatExtra("YesTodayClose", -1);
        mFlushTodayQuote = DBUtils.getTodayQuoteByCode(mNetEaseCode);
//        String code = mNetEaseCode.substring(1);
//        mStockBasicInfo = DBUtils.getTdxStockInfoInstance(code);
        int iDate = getIntent().getIntExtra("XDate", 19700101);
        mTickIDate = iDate;
        mTickDate = Utils.getDateFromIDate(iDate);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_tick_quote);

        mDetailsPanel = findViewById(R.id.tick_detail_panel);
        mLeftTickList = findViewById(R.id.leftTickList);
        mRightTickList = findViewById(R.id.rightTickList);
        mDownloadProgressBar = findViewById(R.id.download_progress);

        mTvBigSeek = findViewById(R.id.big_seek_tv);
        SeekBar seek = findViewById(R.id.big_seek_bar);
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mBigQuoteScale = (float) progress / (float) seekBar.getMax();
                    new Thread(() -> {
                        mTimeShareData.rebuildScatterData(mBigQuoteScale);
                        Message.obtain(mHandler, MSG_UPDATE_CHARTS).sendToTarget();
                    }).start();
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mBigQuoteScale = (float) seek.getProgress() / (float) seek.getMax();

        initTextViews();
        initPriceChart();
        initAmountCharts();
        updateTextViewToXIndex(-1);
        mHandler = new ActivityMessageHandler(this);
        FetchTickDaemon.getInstance().registerListener(this);
    }

    private boolean isTodayTick() {
        return mTickIDate == Utils.getCurrentIDate();
//        return Utils.currentTimeIsTrading();
    }

    @Override
    public void onToastNotify(String fetchNotify) {
        Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
        msg.obj = fetchNotify;
        msg.sendToTarget();
    }

    @Override
    public void onUpdateProgressNotify(int progressPercent) {
//        Log.i(TAG, "receive notify progressPercent=" + progressPercent);
        Message msg = Message.obtain(mHandler, MSG_UPDATE_PROGRESS);
        msg.obj = progressPercent;
        msg.sendToTarget();
    }

    @Override
    public void onShowProgressBar() {
//        Log.i(TAG, "show progress bar");
        Message msg = Message.obtain(mHandler, MSG_SHOW_PROGRESS_BAR);
        msg.sendToTarget();
    }

    @Override
    public void onHideProgressBar() {
//        Log.i(TAG, "hide progress bar");
        Message msg = Message.obtain(mHandler, MSG_HIDE_PROGRESS_BAR);
        msg.sendToTarget();
    }

    public void onTickFetched(String neCode, EmTickType type, Date date, List<TickQuote> tqs) {
        String dateString = Utils.sHyphenDateFormat.format(date);
        if (!mNetEaseCode.equalsIgnoreCase(neCode)) {
            Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
            msg.obj = "分时数据更新，更新股票：" + neCode.substring(1) + ", 非当前股票";
            msg.sendToTarget();
            return;
        }

        int fetchIDate = Utils.getIDateFromDate(date);
        int tickIDate = Utils.getIDateFromDate(mTickDate);
        if (tickIDate != fetchIDate) {
            Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
            msg.obj = "得到的分时数据日期:" + fetchIDate
                    + ", 非目标日期：" + tickIDate;
            msg.sendToTarget();
            return;
        }

        if (tqs == null || tqs.size() <= 0) {
            Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
            msg.obj = "获取" + mName + "(" + neCode.substring(1) + ")" + "在" + dateString + "的分时数据为空";
            msg.sendToTarget();
        } else {
            mTimeShareData = new TickQuoteDataSet(TickQuoteChartActivity.this, tqs, mYesTodayClose);
            mTimeShareData.rebuildScatterData(mBigQuoteScale);
            Message.obtain(mHandler, MSG_UPDATE_CHARTS).sendToTarget();

            Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
            msg.obj = "得到" + mName + "(" + neCode.substring(1) + ")的分时数据，最后时间为:"
                    + dateString + " " + mTimeShareData.getLastTick();
            msg.sendToTarget();
        }

        if (isTodayTick()) {
            TodayQuote quote =
                    DBUtils.flushAndGetTodayQuoteByCode(mNetEaseCode);
            if (null != quote) {
                if (!quote.getBuys().equalsIgnoreCase(mFlushTodayQuote.getBuys()) ||
                    !quote.getSells().equalsIgnoreCase(mFlushTodayQuote.getSells())) {
                    mFlushTodayQuote = quote;
                    Message msg = Message.obtain(mHandler, MSG_SHOW_TOAST);
                    msg.obj = "买5，卖5" + mName + "(" + neCode.substring(1) + ")" + "更新成功";
                    msg.sendToTarget();
                }
            }
        }

    }

}
